package com.quyeying.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.quyeying.entity.TblFollowMerchantEntity;
import com.quyeying.entity.TblMessageEntity;
import com.quyeying.service.TblFollowMerchantService;
import com.quyeying.service.TblMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @ClassName AsyncTask
 * @Description TODO
 * @Author Jll
 * @Date 2022/11/18 16:21
 * @Version 1.0
 */
@Slf4j
@Component
public class AsyncTask {

    @Resource
    private TblFollowMerchantService tblFollowMerchantService;
    @Resource
    private TblMessageService tblMessageService;

    /**
     * 发送发布消息
     */
    @Async("asyncExecutor")
    public void sendMessage(TblMessageEntity messageEntity){
        //查询出关注商户的用户
        QueryWrapper<TblFollowMerchantEntity> followMerchantEntityQueryWrapper = new QueryWrapper<>();
        followMerchantEntityQueryWrapper.eq("merchant_id", messageEntity.getMerchantId());
        List<TblFollowMerchantEntity> merchantEntities = tblFollowMerchantService.list(followMerchantEntityQueryWrapper);
        merchantEntities.stream().forEach(item ->{
            //插入消息
            TblMessageEntity addmessageEntity = new TblMessageEntity();
            addmessageEntity.setMerchantId(messageEntity.getMerchantId());
            addmessageEntity.setUserId(item.getUserId());
            addmessageEntity.setType(messageEntity.getType());
            addmessageEntity.setJoinId(messageEntity.getJoinId());
            addmessageEntity.setIsRead(0);
            QueryWrapper<TblMessageEntity> messageEntityQueryWrapper = new QueryWrapper<>();
            messageEntityQueryWrapper.eq("merchant_id", addmessageEntity.getMerchantId())
                            .eq("user_id", addmessageEntity.getUserId());
            tblMessageService.saveOrUpdate(addmessageEntity,messageEntityQueryWrapper);
        });
    }

}
